package qqserver.service;

import qqcommon.Message;
import qqcommon.MessageType;
import utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 该线程用于服务器推送消息
 */
public class SendNewsToAllService implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("如需启动推送消息功能，请输入: t");
            String input = Utility.readString(100);
            //判断是否输入 't' 以启动推送消息功能
            if (input.equals("t")) {
                boolean loop = true;
                while (loop) {
                    System.out.println("请输入服务器需要推送的信息:(输入 'exit' 表示退出推送服务)");
                    String news = Utility.readString(100);
                    if (news.equals("exit")) {
                        System.out.println("已退出推送服务。");
                        loop = false;
                    } else {
                        startPushMessage(news);
                    }
                }
            }
        }
    }
    public static void startPushMessage(String news) {
            //创建一个message，推送信息
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            message.setSender("服务器");
            message.setContent(news);
            message.setSendTime(new Date().toString());
            System.out.println("服务器推送了消息给所有人(在线): " + news);

            //遍历当前所有的通信线程，得到socket,并发送message
            HashMap<String, ServerConnectClientThread> hashMap = ManageClientThread.getHashMap();
            Iterator<String> iterator = hashMap.keySet().iterator();
            while (iterator.hasNext()) {
                String onlineUserId = iterator.next().toString();
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(
                            hashMap.get(onlineUserId).getSocket().getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

}
